<template>
    <div v-loading="loading">
        <div v-if="!current">
            <el-upload class="upload-demo" :show-file-list="false" :drag="true" :auto-upload="false"
                :on-change="handleChange" :before-upload="beforeUpload" action="#" :accept="accept">
                <i class="el-icon-upload"></i>
                <!-- <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                </div> -->

            </el-upload>
        </div>
        <div v-else>
            <div class="preview-container" @mouseover="mouseover" @mouseleave="mouseleave">
                <el-image lazy :src="current" alt="预览图" class="preview-image" />
                <div class="delete-button-container">
                    <button class="custom-delete-button" @click.stop="deleteImage"
                        :class="{ hovered: deleteButtonHover ? true : false }">
                        <i class="el-icon-delete"></i>
                    </button>
                </div>
            </div>
        </div>

        <div>
            <slot></slot>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        url: { type: String, default: "" },
        prefix: { type: String, default: "banner" },
        accept: { type: String, default: ".jpg, .jpeg, .png, .gif, .webp" },
        showToast: { type: Boolean, default: false },
    },
    data() {
        return {
            loading: false,
            deleteButtonHover: false,
            current: this.url
        };
    },

    mounted() {
        if (this.url) {
            this.current = this.url;
        }
    },
    methods: {

        mouseover() {
            this.deleteButtonHover = true;
        },

        mouseleave() {
            this.deleteButtonHover = false;
        },

        handleChange(file) {
            if (file.status === "ready") {
                this.uploadFile(file.raw);
            }
        },
        beforeUpload(file) {
            const acceptedTypes = this.accept.toLowerCase().split(',').map(type => type.trim());
            const extension = file.name.slice((file.name.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
            const isValidType = acceptedTypes.includes('.' + extension);

            if (!isValidType) {
                this.$message.error(`只能上传以下类型的文件：${this.accept}`);
            }

            return isValidType;
        },

        async uploadFile(file) {
            this.loading = true;
            try {
                const res = await this.$fetch.cosUplod(file, `/assets/${this.prefix}`);
                if (res) {
                    this.showToast && this.$message.success("图片上传成功！");
                    this.update(res);
                } else {
                    throw new Error("图片上传失败");
                }
            } catch (error) {
                console.error("上传错误:", error);
                this.$message.error("图片上传出错，请重试！");
            }
            this.loading = false

        },

        async deleteImage() {
             this.$fetch.post("/api/cos-delete-pc", {
                url: this.url,
            });

            this.update("");

        },

        update(url) {
            this.$emit("update:url", url);
            this.current = url;

        },
    }
};
</script>

<style lang="less" scoped>
.preview-container {
    position: relative;
    display: inline-block;
}

.preview-image {
    width: 100px;
    height: 120px;

    ::v-deep .el-image__inner {
        object-fit: cover;

    }
}

.delete-button-container {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2;
}

.custom-delete-button {
    background-color: rgba(255, 0, 0, 0.8);
    color: white;
    border: none;
    cursor: pointer;
    opacity: 0;
    width: 24px;
    height: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 4px;
    transition: opacity 0.9s ease, transform 0.3s ease;
}

.hovered {
    opacity: 1;
    transform: scale(1);
}

.custom-delete-button i {
    font-size: 16px;
}

.upload-demo {
    display: flex;
    align-items: center;
}

::v-deep .el-upload-dragger {
    display: flex;
    justify-content: center;
    align-items: center;

    .el-icon-upload {
        margin: 0;
    }
}
</style>